package com.ywjt.platformbusiness.store.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.PermissionChecker;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.base.BaseModel;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.my.activity.ActivityAddress;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ywjt.platformbusiness.common.MethodUtils.getUserId;

public class ActivityBusinessPostGoods extends BaseActivity implements View.OnClickListener {
    private static final int REQUEST_CODE = 101;
    private static final Integer REQUESTCODE=10001;
    private static final Integer REQUESTCODE1=10002;

    private LinearLayout llPost,llHarvest,llPostAddress,llHarvestAddress;
    private TextView tvPostUserName,tvPostDefault,tvHarvestDefault,tvPostAddressDetail,
            tvHarvestUserName,tvHavestAddressdetail;
    private ImageView ivHarvestIsDefault,ivPostIsDefault;
    private EditText etGoodsName,etGoodsNum,etWeight;
    private TextView tvConfirm;
    private ImageView ivSelect;

    private String name="";//物品名称
    private String num="";//物品数量
    private String weight="";//物品重量
    private String mailAddress="";//寄件地址id
    private String receiveAddress="";//收货地址id
    private String  lat="",lng=""; //113.784208  34.758762

    private Boolean isSelect=false;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, ActivityBusinessPostGoods.class);
        context.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llPost:
                Intent intent=new Intent(ActivityBusinessPostGoods.this, ActivityAddress.class);
                intent.putExtra("flag", REQUESTCODE);
                intent.putExtra("type",2);
                startActivityForResult(intent, REQUESTCODE);
                break;
            case R.id.llHarvest:
                Intent intent1=new Intent(ActivityBusinessPostGoods.this, ActivityAddress.class);
                intent1.putExtra("flag", REQUESTCODE1);
                intent1.putExtra("type",2);
                startActivityForResult(intent1, REQUESTCODE1);
                break;
            case R.id.tvConfirm:
                //立即下单
                if (isSelect){
                    addOshopCentreMail();
                }else {
                    Toast.makeText(ActivityBusinessPostGoods.this,"请先同意并选中服务协议",Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
            case R.id.ivSelect:
                if (!isSelect){
                    ivSelect.setImageResource(R.mipmap.icon_address_selected);
                }else {
                    ivSelect.setImageResource(R.mipmap.icon_address_unselected);
                }
                isSelect=!isSelect;
                break;
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.postgoods_activity;
    }

    @Override
    protected void initView() {
        setTitleText("寄件");
        llPost=findViewById(R.id.llPost);
        tvPostUserName=findViewById(R.id.tvPostUserName);
        llPostAddress=findViewById(R.id.llPostAddress);
        tvPostDefault=findViewById(R.id.tvPostDefault);
        ivPostIsDefault=findViewById(R.id.ivPostIsDefault);
        etGoodsName=findViewById(R.id.etGoodsName);
        ivHarvestIsDefault=findViewById(R.id.ivHarvestIsDefault);
        tvPostAddressDetail=findViewById(R.id.tvPostAddressDetail);
        tvHarvestDefault=findViewById(R.id.tvHarvestDefault);
        llHarvestAddress=findViewById(R.id.llHarvestAddress);
        ivSelect=findViewById(R.id.ivSelect);
        tvHarvestUserName=findViewById(R.id.tvHarvestUserName);
        tvHavestAddressdetail=findViewById(R.id.tvHavestAddressdetail);
        tvConfirm=findViewById(R.id.tvConfirm);
        etGoodsNum=findViewById(R.id.etGoodsNum);
        etWeight=findViewById(R.id.etWeight);
        llPost.setOnClickListener(this::onClick);
        ivSelect.setOnClickListener(this::onClick);
        llHarvest=findViewById(R.id.llHarvest);
        llHarvest.setOnClickListener(this::onClick);
        tvConfirm.setOnClickListener(this::onClick);

        etGoodsName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                name=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etGoodsNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                num=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        etWeight.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                weight=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        checkPermission();
    }

    @Override
    protected void initData() { }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return 0;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode==RESULT_OK){
            if (requestCode==REQUESTCODE){
                tvPostDefault.setVisibility(View.GONE);
                llPostAddress.setVisibility(View.VISIBLE);
                tvPostUserName.setText(data.getStringExtra("name")+"  "+data.getStringExtra("phone"));
                tvPostAddressDetail.setText("地址："+data.getStringExtra("address"));
                mailAddress=data.getStringExtra("userAddressId");
                if (data.getIntExtra("isDefault",0)==0){
                    ivPostIsDefault.setVisibility(View.GONE);
                }else {
                    ivPostIsDefault.setVisibility(View.VISIBLE);
                }
            }else if(requestCode==REQUESTCODE1){
                llHarvestAddress.setVisibility(View.VISIBLE);
                tvHarvestDefault.setVisibility(View.GONE);
                tvHarvestUserName.setText(data.getStringExtra("name")+"  "+data.getStringExtra("phone"));
                tvHavestAddressdetail.setText("地址："+data.getStringExtra("address"));
                receiveAddress=data.getStringExtra("userAddressId");
                if (data.getIntExtra("isDefault",0)==0){
                    ivHarvestIsDefault.setVisibility(View.GONE);
                }else {
                    ivHarvestIsDefault.setVisibility(View.VISIBLE);
                }
            }
        }
    }


    //添加地址
    public void addOshopCentreMail(){
        Map map = new HashMap();

        if (mailAddress.equals("")){
            Toast.makeText(ActivityBusinessPostGoods.this,"请选择寄件地址",Toast.LENGTH_SHORT).show();
            return ;
        }
        if (receiveAddress.equals("")){
            Toast.makeText(ActivityBusinessPostGoods.this,"请选择收件地址",Toast.LENGTH_SHORT).show();
            return ;
        }
        if (name.equals("")){
            Toast.makeText(ActivityBusinessPostGoods.this,"请填写物品名称",Toast.LENGTH_SHORT).show();
            return ;
        }
        if (num.equals("")){
            Toast.makeText(ActivityBusinessPostGoods.this,"请填写物品数量",Toast.LENGTH_SHORT).show();
            return ;
        }

        if (weight.equals("")){
            Toast.makeText(ActivityBusinessPostGoods.this,"请填写物品数量",Toast.LENGTH_SHORT).show();
            return;
        }


        map.put("mailAddress", mailAddress);
        map.put("name",name);
        map.put("receiveAddress",receiveAddress);
        map.put("num",num);
        map.put("senderId",getUserId(ActivityBusinessPostGoods.this));
        map.put("weight",weight);
        map.put("lngStr",lat+","+lng);

        new HttpRequest(getContext()).doGet(UrlConstants.merchant_shopCentreMail, "", map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        finish();
                    }else {
                        Toast.makeText(ActivityBusinessPostGoods.this,message,Toast .LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }


    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //可在其中解析amapLocation获取相应内容。
                    lat=amapLocation.getLatitude()+"";
                    lng=amapLocation.getLongitude()+"";
                    Log.e("aaaaaa",lat+":::"+lng);
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };
    //声明AMapLocationClientOption对象
    public AMapLocationClientOption mLocationOption = null;
    public void initLocation(){

//初始化定位
        mLocationClient = new AMapLocationClient(ActivityBusinessPostGoods.this);
//设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
//初始化AMapLocationClientOption对象
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
        mLocationOption.setHttpTimeOut(20000);
        //关闭缓存机制
        mLocationOption.setLocationCacheEnable(false);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
//启动定位
        mLocationClient.startLocation();
    }


    @SuppressLint("MissingSuperCall")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("aaa", "onRequestPermissionsResult: " +
                            "权限申请成功");
                    for (int i : grantResults) {
                        Log.d("aaa", "onRequestPermissionsResult: " + i);
                    }
                    initLocation();
                } else {
                    Toast.makeText(ActivityBusinessPostGoods.this, "您已拒绝申请权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }



    /****权限**/
    private void checkPermission(){
        try{
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (PermissionChecker.checkSelfPermission(ActivityBusinessPostGoods.this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PermissionChecker.PERMISSION_GRANTED||
                        PermissionChecker.checkSelfPermission(ActivityBusinessPostGoods.this,Manifest.permission.ACCESS_BACKGROUND_LOCATION)!=PermissionChecker.PERMISSION_GRANTED) {
                    // 不相等 请求授权
                    ActivityCompat.requestPermissions((Activity) ActivityBusinessPostGoods.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_BACKGROUND_LOCATION
                    },REQUEST_CODE);
                }else {
                    initLocation();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

}